package com.kuang.sync;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class ExternalApiServiceImpl implements ExternalApiService{

    @Value("${mqtt.sfurl}")
    String url;

    @Override
    public String callExternalApi() throws RestClientException {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String requestBody = "{\"key\": \"value\"}";
        // requestBody 参数也可以是任意类型(泛型)
        // public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers)

        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
        String responseBody = response.getBody();
        // 对响应进行处理
        // 比如转成map
        Map<String, Object> map = JSONObject.parseObject(responseBody);
        //在这个示例中，我们使用postForEntity()方法发送POST请求，并在请求体中传递了JSON

        return "";
    }

    @Override
    public String putPayEntityAdd(String json) throws RestClientException {
        RestTemplate restTemplate = new RestTemplate();
        //String url = "http://127.0.0.1:8081/sync/hello";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String requestBody = json;

        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
        String responseBody = response.getBody();
        // 对响应进行处理
        // 比如转成map
        Map<String, Object> map = JSONObject.parseObject(responseBody);
        //在这个示例中，我们使用postForEntity()方法发送POST请求，并在请求体中传递了JSON

        return "";
    }
}